<template>
  <page-layout :show-back="true" title="帖子详情" @back="goBack">
    <!-- 帖子内容区域 -->
    <scroll-view class="post-content" scroll-y="true" @scrolltolower="loadMoreComments">
      <!-- 帖子主体 -->
      <view class="post-main">
        <!-- 用户信息 -->
        <view class="user-info">
          <image class="avatar" :src="post.avatar" mode="aspectFill"></image>
          <view class="user-detail">
            <view class="username">{{ post.username }}</view>
            <view class="post-meta">
              <text class="post-time">{{ post.createTime }}</text>
              <text class="post-location" v-if="post.location">· {{ post.location }}</text>
            </view>
          </view>
          <view class="follow-btn" v-if="!post.isFollowing" @tap="followUser">关注</view>
        </view>

        <!-- 帖子内容 -->
        <view class="post-text">
          <view class="post-title" v-if="post.title">{{ post.title }}</view>
          <text class="post-content-text">{{ post.content }}</text>
        </view>

        <!-- 帖子图片 -->
        <view class="post-images" v-if="post.images && post.images.length">
          <view class="image-grid" :class="'grid-' + post.images.length">
            <image
                v-for="(img, index) in post.images"
                :key="index"
                :src="img"
                mode="aspectFill"
                @tap="previewImage(index)"
                class="post-image"
            ></image>
          </view>
        </view>

        <!-- 帖子标签 -->
        <view class="post-tags" v-if="post.tags && post.tags.length">
          <view class="tag-item" v-for="(tag, index) in post.tags" :key="index" @tap="goToTag(tag)">
            # {{ tag }}
          </view>
        </view>

        <!-- 帖子数据 -->
        <view class="post-stats">
          <view class="stat-item" @tap="toggleLike">
            <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="20"
                       :color="post.isLiked ? '#ff5a5f' : '#999'"></uni-icons>
            <text :class="{'active': post.isLiked}">{{ post.likes }}</text>
          </view>
          <view class="stat-item">
            <uni-icons type="chat" size="20" color="#999"></uni-icons>
            <text>{{ post.comments }}</text>
          </view>
          <view class="stat-item" @tap="sharePost">
            <uni-icons type="redo" size="20" color="#999"></uni-icons>
            <text>分享</text>
          </view>
        </view>
      </view>

      <!-- 评论区 -->
      <view class="comments-section">
        <view class="section-header">
          <text class="section-title">评论 {{ post.comments }}</text>
          <view class="sort-options">
            <text
                class="sort-option"
                :class="{'active': commentSort === 'hot'}"
                @tap="changeSort('hot')"
            >热门
            </text>
            <text class="divider">|</text>
            <text
                class="sort-option"
                :class="{'active': commentSort === 'latest'}"
                @tap="changeSort('latest')"
            >最新
            </text>
          </view>
        </view>

        <!-- 评论列表 -->
        <view class="comment-list">
          <view class="comment-item" v-for="(comment, index) in commentList" :key="index">
            <image class="comment-avatar" :src="comment.avatar" mode="aspectFill"></image>
            <view class="comment-body">
              <view class="comment-user">{{ comment.username }}</view>
              <view class="comment-content">{{ comment.content }}</view>
              <view class="comment-footer">
                <text class="comment-time">{{ comment.createTime }}</text>
                <view class="comment-actions">
                  <view class="action-item reply" @tap="replyComment(comment)">回复</view>
                  <view class="action-item like" @tap="likeComment(index)" :class="{'active': comment.isLiked}">
                    <uni-icons :type="comment.isLiked ? 'heart-filled' : 'heart'" size="12"
                               :color="comment.isLiked ? '#ff5a5f' : '#999'"></uni-icons>
                    <text>{{ comment.likes || '点赞' }}</text>
                  </view>
                </view>
              </view>

              <!-- 回复列表 -->
              <view class="replies" v-if="comment.replies && comment.replies.length">
                <view class="reply-item" v-for="(reply, rIndex) in comment.replies" :key="rIndex">
                  <view class="reply-user">{{ reply.username }}</view>
                  <text class="reply-to" v-if="reply.replyTo">回复</text>
                  <view class="reply-target" v-if="reply.replyTo">{{ reply.replyTo }}</view>
                  <view class="reply-content">{{ reply.content }}</view>
                </view>
                <view class="view-more" v-if="comment.replyCount > comment.replies.length"
                      @tap="viewMoreReplies(comment)">
                  查看全部{{ comment.replyCount }}条回复
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多 -->
          <view class="loading-more" v-if="isLoadingMore">
            <uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
            <text>加载中...</text>
          </view>
          <view class="no-more" v-if="noMoreComments">没有更多评论了</view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部评论栏 -->
    <view class="comment-bar">
      <view class="comment-input-wrapper" @tap="focusCommentInput">
        <input
            class="comment-input"
            type="text"
            v-model="commentText"
            placeholder="说点什么..."
            :focus="inputFocus"
            confirm-type="send"
            @confirm="submitComment"
        />
      </view>
      <view class="comment-actions">
        <view class="action-btn" @tap="toggleLike">
          <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" size="24"
                     :color="post.isLiked ? '#ff5a5f' : '#999'"></uni-icons>
        </view>
        <view class="action-btn" @tap="sharePost">
          <uni-icons type="redo" size="24" color="#999"></uni-icons>
        </view>
      </view>
    </view>
  </page-layout>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
import PageLayout from '@/components/PageLayout.vue';

// 帖子数据
const post = reactive({
  id: 1,
  username: '蓝记用户',
  avatar: '/static/images/avatar.jpg',
  createTime: '2小时前',
  location: '北京市朝阳区',
  title: '这是一个测试帖子标题',
  content: '这是帖子内容，可以很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长',
  images: [
    '/static/images/post1.jpg',
    '/static/images/post2.jpg',
    '/static/images/post3.jpg',
  ],
  tags: ['生活记录', '美食分享'],
  likes: 128,
  comments: 32,
  isLiked: false,
  isFollowing: false
});

// 评论相关
const commentList = ref([]);
const commentSort = ref('hot');
const commentText = ref('');
const inputFocus = ref(false);
const isLoadingMore = ref(false);
const noMoreComments = ref(false);
const currentPage = ref(1);

// 生成模拟评论数据
const generateComments = (page, sort) => {
  const comments = [];
  const startIndex = (page - 1) * 10;
  const count = page === 1 ? 10 : Math.floor(Math.random() * 5) + 3;

  for (let i = 0; i < count; i++) {
    const hasReplies = Math.random() > 0.5;
    const replyCount = hasReplies ? Math.floor(Math.random() * 10) + 1 : 0;
    const replies = [];

    if (hasReplies) {
      const visibleReplies = Math.min(replyCount, 2);
      for (let j = 0; j < visibleReplies; j++) {
        replies.push({
          username: `用户${Math.floor(Math.random() * 1000)}`,
          replyTo: j > 0 ? `用户${Math.floor(Math.random() * 1000)}` : '',
          content: `这是回复内容${j + 1}，回复内容可以很长很长很长很长很长很长很长很长`,
          createTime: '1小时前'
        });
      }
    }

    comments.push({
      id: startIndex + i + 1,
      username: `用户${Math.floor(Math.random() * 1000)}`,
      avatar: '/static/images/avatar.jpg',
      content: `这是评论内容${startIndex + i + 1}，评论内容可以很长很长很长很长很长很长很长很长很长很长很长很长`,
      createTime: `${Math.floor(Math.random() * 24)}小时前`,
      likes: Math.floor(Math.random() * 100),
      isLiked: false,
      replyCount,
      replies
    });
  }

  // 根据排序方式排序
  if (sort === 'hot') {
    comments.sort((a, b) => b.likes - a.likes);
  } else {
    comments.sort((a, b) => parseInt(a.createTime) - parseInt(b.createTime));
  }

  return comments;
};

// 加载评论
const loadComments = (refresh = false) => {
  if (refresh) {
    commentList.value = [];
    currentPage.value = 1;
    noMoreComments.value = false;
  }

  const newComments = generateComments(currentPage.value, commentSort.value);
  commentList.value = [...commentList.value, ...newComments];

  // 模拟没有更多评论
  if (currentPage.value >= 3 || newComments.length < 5) {
    noMoreComments.value = true;
  }
};

// 加载更多评论
const loadMoreComments = () => {
  if (noMoreComments.value || isLoadingMore.value) return;

  isLoadingMore.value = true;
  currentPage.value++;

  setTimeout(() => {
    loadComments();
    isLoadingMore.value = false;
  }, 1000);
};

// 切换评论排序
const changeSort = (sort) => {
  if (commentSort.value === sort) return;
  commentSort.value = sort;
  loadComments(true);
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: post.images
  });
};

// 点赞帖子
const toggleLike = () => {
  post.isLiked = !post.isLiked;
  post.likes += post.isLiked ? 1 : -1;
};

// 关注用户
const followUser = () => {
  post.isFollowing = true;
  uni.showToast({
    title: '关注成功',
    icon: 'success'
  });
};

// 分享帖子
const sharePost = () => {
  uni.showActionSheet({
    itemList: ['分享到微信', '复制链接', '分享到朋友圈'],
    success: function (res) {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    }
  });
};

// 点赞评论
const likeComment = (index) => {
  const comment = commentList.value[index];
  comment.isLiked = !comment.isLiked;
  comment.likes += comment.isLiked ? 1 : -1;
};

// 回复评论
const replyComment = (comment) => {
  commentText.value = `回复 @${comment.username}: `;
  inputFocus.value = true;
};

// 查看更多回复
const viewMoreReplies = (comment) => {
  uni.showToast({
    title: '查看更多回复功能开发中',
    icon: 'none'
  });
};

// 聚焦评论输入框
const focusCommentInput = () => {
  inputFocus.value = true;
};

// 提交评论
const submitComment = () => {
  if (!commentText.value.trim()) return;

  // 模拟提交评论
  const newComment = {
    id: commentList.value.length + 1,
    username: '我',
    avatar: '/static/images/avatar.jpg',
    content: commentText.value,
    createTime: '刚刚',
    likes: 0,
    isLiked: false,
    replyCount: 0,
    replies: []
  };

  // 添加到评论列表顶部
  if (commentSort.value === 'latest') {
    commentList.value.unshift(newComment);
  } else {
    commentList.value.push(newComment);
  }

  // 更新评论数
  post.comments++;

  // 清空输入框
  commentText.value = '';
  inputFocus.value = false;

  uni.showToast({
    title: '评论成功',
    icon: 'success'
  });
};

// 前往标签页
const goToTag = (tag) => {
  uni.showToast({
    title: `前往${tag}话题`,
    icon: 'none'
  });
};

// 页面加载
onMounted(() => {
  // 加载评论
  loadComments();
});
</script>

<style lang="scss">
page {
  background-color: #f5f7fa;
  height: 100%;
}

/* 帖子内容区域 */
.post-content {
  flex: 1;
  box-sizing: border-box;
}

/* 帖子主体 */
.post-main {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-detail {
  flex: 1;
}

.username {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 6rpx;
}

.post-meta {
  font-size: 24rpx;
  color: #999;
}

.post-location {
  margin-left: 10rpx;
}

.follow-btn {
  padding: 10rpx 20rpx;
  background-color: #f0f2f5;
  color: #333;
  font-size: 24rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
}

/* 帖子内容 */
.post-text {
  margin-bottom: 20rpx;
}

.post-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.post-content-text {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
}

/* 帖子图片 */
.post-images {
  margin-bottom: 20rpx;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
}

.post-image {
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.grid-1 .post-image {
  width: 500rpx;
  height: 500rpx;
}

.grid-2 .post-image,
.grid-4 .post-image {
  width: 340rpx;
  height: 340rpx;
}

.grid-3 .post-image,
.grid-5 .post-image,
.grid-6 .post-image,
.grid-7 .post-image,
.grid-8 .post-image,
.grid-9 .post-image {
  width: 220rpx;
  height: 220rpx;
}

/* 帖子标签 */
.post-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.tag-item {
  font-size: 26rpx;
  color: #6e8efb;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
}

/* 帖子数据 */
.post-stats {
  display: flex;
  border-top: 1rpx solid #ebedf0;
  padding-top: 20rpx;
}

.stat-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #999;
}

.stat-item text {
  margin-left: 10rpx;
}

.stat-item .active {
  color: #ff5a5f;
}

/* 评论区 */
.comments-section {
  background-color: #fff;
  padding: 30rpx;
  padding-bottom: 120rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.sort-options {
  font-size: 26rpx;
  color: #999;
}

.sort-option {
  padding: 0 10rpx;
}

.sort-option.active {
  color: #333;
  font-weight: 500;
}

.divider {
  color: #ebedf0;
}

/* 评论列表 */
.comment-item {
  display: flex;
  margin-bottom: 30rpx;
}

.comment-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.comment-body {
  flex: 1;
}

.comment-user {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
}

.comment-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10rpx;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.comment-time {
  font-size: 24rpx;
  color: #999;
}

.comment-actions {
  display: flex;
  align-items: center;
}

.action-item {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}

.action-item.active {
  color: #ff5a5f;
}

.action-item text {
  margin-left: 6rpx;
}

/* 回复列表 */
.replies {
  background-color: #f5f7fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 10rpx;
}

.reply-item {
  display: flex;
  flex-wrap: wrap;
  font-size: 26rpx;
  margin-bottom: 16rpx;
}

.reply-user {
  color: #6e8efb;
  margin-right: 10rpx;
}

.reply-to {
  color: #999;
  margin-right: 10rpx;
}

.reply-target {
  color: #6e8efb;
  margin-right: 10rpx;
}

.reply-content {
  color: #333;
  width: 100%;
  margin-top: 6rpx;
}

.view-more {
  font-size: 26rpx;
  color: #6e8efb;
  text-align: center;
}

/* 加载更多 */
.loading-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  font-size: 26rpx;
  color: #999;
}

.loading-more text {
  margin-left: 10rpx;
}

/* 底部评论栏 */
.comment-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-top: 1rpx solid #ebedf0;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  z-index: 100;
}

.comment-input-wrapper {
  flex: 1;
  background-color: #f5f7fa;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
}

.comment-input {
  width: 100%;
  height: 70rpx;
  font-size: 28rpx;
}

.comment-actions {
  display: flex;
  margin-left: 20rpx;
}

.action-btn {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>